//
//  UIImageView+Download.m
//  Budejie
//
//  Created by 远成物流 on 2017/5/25.
//  Copyright © 2017年 陈梦佳. All rights reserved.
//

#import "UIImageView+Download.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "UIImage+DealImage.h"
#import <AFNetworking/AFNetworking.h>

@implementation UIImageView (Download)

-(void)setImageWithUrl:(NSString *)url{
    UIImage *placeholder = [UIImage imageNamed:@"defaultUserIcon"];
    [self sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:placeholder completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        // 图片下载失败，直接返回，按照它的默认做法
        if (!image) {
            return ;
        }
        
        [self.image circleImage];
    }];
}

-(void)setOriginalImage:(NSString *)originalImg thumbnailImage:(NSString *)thumbnailImg placeholderImage:(UIImage *)placeholderImg completed:(SDExternalCompletionBlock)completed{
    
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager manager];
    
    //从缓存中获取原图
    UIImage *originImg = [[SDImageCache sharedImageCache] imageFromCacheForKey:originalImg];
    if (originImg) {
        //有缓存
        [self sd_setImageWithURL:[NSURL URLWithString:originalImg] placeholderImage:placeholderImg completed:completed];
    }else{
        //无缓存
        if (mgr.isReachableViaWiFi) {
            //wifi
            [self sd_setImageWithURL:[NSURL URLWithString:originalImg] placeholderImage:placeholderImg completed:completed];
        }else if(mgr.isReachableViaWWAN){
            //3g、4g
            BOOL downloadImageWhen3GOr4G = YES;
            if (downloadImageWhen3GOr4G) {
                //3g网络下允许下载图片，加载原图
                [self sd_setImageWithURL:[NSURL URLWithString:originalImg] placeholderImage:placeholderImg completed:completed];
            }else{
                //下载缩略图
                [self sd_setImageWithURL:[NSURL URLWithString:thumbnailImg] placeholderImage:placeholderImg completed:completed];
            }
        }else{
            //没有网
            UIImage *thumbnail = [[SDImageCache sharedImageCache] imageFromCacheForKey:thumbnailImg];
            if (thumbnail) {
                //有缓存缩略图
                [self sd_setImageWithURL:[NSURL URLWithString:thumbnailImg] placeholderImage:placeholderImg completed:completed];
            }else{
                [self sd_setImageWithURL:nil placeholderImage:placeholderImg completed:completed];
            }
        }
    }
}

@end
